function backgroundScript() {
    onMainUiReady(function() {
        proxyNotifications(!0),
        checkBadge(!1),
        reCheckBadge()
    }),
    reCheckLoadingError()
}
function foregroundScript() {
    onMainUiReady(function() {
        proxyNotifications(!1),
        checkBadge(!1),
        reCheckBadge(),
        checkSrcChat(),
        checkMyNum()
    })
}
function onMainUiReady(a) {
    try {
        if (void 0 != document.querySelector(".app-wrapper > .app")) debug && console.info("WANote: Found main UI, will notify main UI ready event directly"),
        setTimeout(function() {
            a()
        },
        safetyDelayShort);
        else {
            debug && console.info("WANote: Setting up mutation observer for main UI ready event...");
            var b = document.getElementById("app");
            if (void 0 != b) {
                var c = new MutationObserver(function(b) {
                    debug && console.info("WANote: Mutation observerd, will search main UI");
                    for (var d = !1,
                    e = 0; e < b.length; e++) {
                        for (var f = (b[e], b[e].addedNodes), g = 0; g < f.length; g++) {
                            var h = f[g];
                            if ("div" == h.nodeName.toLowerCase() && h.classList.contains("app")) {
                                debug && console.info("WANote: Found main UI, will notify main UI ready event"),
                                c.disconnect(),
                                setTimeout(function() {
                                    a()
                                },
                                safetyDelayShort),
                                d = !0;
                                break
                            }
                        }
                        if (d) break
                    }
                });
                c.observe(b, {
                    childList: !0,
                    subtree: !0
                })
            }
        }
    } catch(d) {
        console.error("WANote: Exception while setting up mutation observer for main UI ready event"),
        console.error(d)
    }
}
function proxyNotifications(a) {
    a ? window.addEventListener("message",
    function(a) {
        void 0 != a && void 0 != a.data && "backgroundNotificationClicked" == a.data.name && chrome.runtime.sendMessage({
            name: "backgroundNotificationClicked",
            srcChatTitle: a.data.srcChatTitle
        })
    }) : window.addEventListener("message",
    function(a) {
        if (void 0 == a || void 0 == a.data || "foregroundNotificationClicked" != a.data.name && "foregroundNotificationShown" != a.data.name) {
            if (void 0 != a && void 0 != a.data && "chat" == a.data.name) {
                var b = JSON.parse(a.data.chat),
                c = "";
                "undefined" != typeof a.data.cid && (c = a.data.cid),
                chrome.runtime.sendMessage({
                    name: "myChats",
                    chats: JSON.stringify(b.msgs),
                    id: b.id,
                    cid: c
                })
            }
        } else setTimeout(function() {
            checkBadge(!1)
        },
        safetyDelayLong)
    });
    var b = "";
    b += "var debug = " + debug + ";",
    b += "var isBackgroundScript = " + a + ";",
    b += "var backgroundNotif = " + backgroundNotif + ";",
    b += "(" +
    function() {
        var b = window.Notification,
        c = function(c, d) {
            if (a && !backgroundNotif) return void(debug && console.info("WANote: Notification creation intercepted, will not proxy it because the user disabled background notifications"));
            debug && console.info("WANote: Notification creation intercepted, will proxy it");
            var e = new b(c, d);
            this.title = e.title,
            this.dir = e.dir,
            this.lang = e.lang,
            this.body = e.body,
            this.tag = e.tag,
            this.icon = e.icon;
            var f = this;
            e.onclick = function(b) {
                if (void 0 != f.onclick && f.onclick(b), a) {
                    var c = void 0;
                    void 0 != b && void 0 != b.srcElement && "string" == typeof b.srcElement.title && b.srcElement.title.length > 0 && (c = b.srcElement.title, debug && console.info("WANote: Background notification click intercepted with srcChatTitle " + c)),
                    window.postMessage({
                        name: "backgroundNotificationClicked",
                        srcChatTitle: c
                    },
                    "*")
                } else debug && console.info("WANote: Foreground notification click intercepted"),
                window.postMessage({
                    name: "foregroundNotificationClicked"
                },
                "*")
            },
            e.onshow = function(b) {
                void 0 != f.onshow && f.onshow(b),
                a || (debug && console.info("WANote: Foreground notification show intercepted"), window.postMessage({
                    name: "foregroundNotificationShown"
                },
                "*"))
            },
            e.onerror = function(a) {
                void 0 != f.onerror && f.onerror(a)
            },
            e.onclose = function(a) {
                void 0 != f.onclose && f.onclose(a)
            },
            this.close = function() {
                e.close()
            },
            this.addEventListener = function(a, b, c) {
                e.addEventListener(a, b, c)
            },
            this.removeEventListener = function(a, b, c) {
                e.removeEventListener(a, b, c)
            },
            this.dispatchEvent = function(a) {
                e.dispatchEvent(a)
            }
        };
        c.permission = b.permission,
        c.requestPermission = b.requestPermission,
        window.Notification = c
    } + ")();";
    var c = document.createElement("script");
    c.innerHTML = b,
    document.head.appendChild(c)
}
function reCheckBadge() {
    setTimeout(function() {
        checkBadge(!0)
    },
    checkBadgeInterval)
}
function checkBadge(a) {
    debugRepeating && console.info("WANote: Checking badge...");
    try {
        var b = document.getElementsByClassName("pane-list-user").length > 0,
        c = !b || document.getElementsByClassName("butterbar-phone").length > 0 || document.getElementsByClassName("butterbar-computer").length > 0;
        if (b) {
            for (var d = 0,
            e = "",
            f = document.getElementsByClassName("chat unread"), g = 0; g < f.length; g++) {
                if (unreadChatElem = f[g], document.getElementsByClassName("chat unread")[0].getElementsByClassName("chat-secondary")[0].getElementsByClassName("chat-meta")[0].getElementsByTagName("span")[1].hasAttribute("data-icon")) var h = parseInt(document.getElementsByClassName("chat unread")[0].getElementsByClassName("chat-secondary")[0].getElementsByClassName("chat-meta")[0].getElementsByTagName("span")[2].textContent);
                else var h = parseInt(document.getElementsByClassName("chat unread")[0].getElementsByClassName("chat-secondary")[0].getElementsByClassName("chat-meta")[0].getElementsByTagName("span")[1].textContent);
                var i = unreadChatElem.getElementsByClassName("chat-title")[0].textContent;
                i.length > 30 && (i = i.substr(0, 27) + "...");
                var j = unreadChatElem.getElementsByClassName("chat-status")[0].textContent;
                j.length > 70 && (j = j.substr(0, 67) + "...");
                var k = "";
                unreadChatElem.getElementsByClassName("chat-time").length > 0 && (k = "[" + unreadChatElem.getElementsByClassName("chat-time")[0].textContent + "]"),
                d += h,
                e += (g > 0 ? "\n": "") + "(" + h + ")  " + i + "  →  " + j + "  " + k
            }
            var l = "";
            d > 0 && (l = d.toString()),
            0 == e.length && (e = "Open WhatsApp"),
            lastToolbarIconWarn !== c || lastToolbarIconBadgeText !== l || lastToolbarIconTooltipText !== e ? (debug && console.info("WANote: Will update toolbar icon info"), chrome.runtime.sendMessage({
                name: "setToolbarIcon",
                warn: c,
                badgeText: l,
                tooltipText: e
            }), lastToolbarIconWarn = c, lastToolbarIconBadgeText = l, lastToolbarIconTooltipText = e) : debugRepeating && console.info("WANote: Will not update toolbar icon info because it did not change")
        } else lastToolbarIconWarn !== c ? (debug && console.info("WANote: Will update toolbar icon warning info"), chrome.runtime.sendMessage({
            name: "setToolbarIcon",
            warn: c
        }), lastToolbarIconWarn = c) : debugRepeating && console.info("WANote: Will not update toolbar icon warning info because it did not change")
    } catch(m) {
        console.error("WANote: Exception while checking badge"),
        console.error(m)
    }
    a && reCheckBadge()
}
function reCheckLoadingError() {
    setTimeout(function() {
        checkLoadingError()
    },
    checkLoadingErrorInterval)
}
function checkLoadingError() {
    debug && console.info("WANote: Checking potential loading error...");
    try {
        var a = document.getElementsByClassName("spinner").length > 0;
        a && !lastPotentialLoadingError && debug && console.warn("WANote: Found potential loading error"),
        lastPotentialLoadingError && a ? (debug && console.warn("WANote: Found loading error, will reload"), window.location.href = whatsAppUrl) : lastPotentialLoadingError = a
    } catch(b) {
        console.error("WANote: Exception while checking loading error"),
        console.error(b)
    }
    reCheckLoadingError()
}
function checkSrcChat() {
    debug && console.info("WANote: Checking source chat...");
    try {
        var a = window.location.hash,
        b = document.getElementById("app").innerHTML;
        debug && console.info("FRAGMENT: " + a),
        debug && console.info("TEXTO: " + b);
        var c = document.getElementsByClassName("chat"),
        d = [];
        for (m = 0; m < c.length; m++) {
            var e = "",
            f = c[m].getElementsByClassName("avatar"),
            e = f[0].getElementsByTagName("img");
            if (e.length > 0) {
                var g = e[0].src,
                h = c[m].getElementsByClassName("chat-title");
                d.push({
                    avatar: g,
                    title: h[0].innerText
                })
            }
        }
        if (chrome.runtime.sendMessage({
            from: "content",
            subject: "channels",
            channels: d
        }), "string" == typeof a && 0 == a.indexOf(sourceChatFragment)) {
            var i = decodeURIComponent(a.substr(sourceChatFragment.length)),
            j = void 0,
            k = !1;
            if (!k) for (var l = document.querySelectorAll(".first .chat-title .emojitext"), m = 0; m < l.length; m++) {
                j = l[m];
                var n = j.getAttribute("title");
                if ("string" == typeof n && n == i) {
                    k = !0;
                    break
                }
            }
            if (!k) for (var l = document.querySelectorAll(".unread .chat-title .emojitext"), m = 0; m < l.length; m++) {
                j = l[m];
                var n = j.getAttribute("title");
                if ("string" == typeof n && n == i) {
                    k = !0;
                    break
                }
            }
            if (!k) for (var l = document.querySelectorAll(".chat-title .emojitext"), m = 0; m < l.length; m++) {
                j = l[m];
                var n = j.getAttribute("title");
                if ("string" == typeof n && n == i) {
                    k = !0;
                    break
                }
            }
            k && (debug && console.info("WANote: Found source chat, will click it"), history.replaceState({},
            document.title, "/"), setTimeout(function() {
                j.dispatchEvent(new MouseEvent("mousedown", {
                    bubbles: !0,
                    cancelable: !0
                }))
            },
            safetyDelayShort))
        }
    } catch(o) {
        console.error("WANote: Exception while checking source chat"),
        console.error(o)
    }
}
function checkMyNum() {
    debug && console.info("WANote: Checking myprofile...");
    try {
        var a = document.getElementsByClassName("pane-list-user");
        if (a.length < 1) return void window.setTimeout(checkMyNum, 1e3);
        var b = a[0].getElementsByClassName("icon-user-default");
        if (b.length < 1) return void window.setTimeout(checkMyNum, 1e3);
        var c = b[0].getElementsByClassName("avatar-body");
        if (c.length < 1) return void window.setTimeout(checkMyNum, 1e3);
        var d = c[0].getElementsByTagName("img"),
        e = d[0].src,
        f = e.substr(e.indexOf("&u=") + 3);
        if (f = f.substr(0, f.indexOf("%40")), f.length < 1) return void window.setTimeout(checkMyNum, 1e3);
        chrome.runtime.sendMessage({
            from: "content",
            subject: "avatar",
            avatar: e,
            number: f
        }),
        toDataURL(e,
        function(a) {
            chrome.runtime.sendMessage({
                from: "content",
                subject: "avatar",
                avatar: a
            })
        })
    } catch(g) {
        console.error("WANote: Exception while checking avatar"),
        console.error(g)
    }
}
function toDataURL(a, b, c) {
    var d = new Image;
    d.crossOrigin = "Anonymous",
    d.onload = function() {
        var a, d = document.createElement("CANVAS"),
        e = d.getContext("2d");
        d.height = this.height,
        d.width = this.width,
        e.drawImage(this, 0, 0),
        a = d.toDataURL(c),
        b(a)
    },
    d.src = a,
    (d.complete || void 0 === d.complete) && (d.src = "", d.src = a)
}
function addOptions() {
    debug && console.info("WANote: Adding options...");
    try {
        var a = document.getElementsByClassName("menu-item")[0];
        if (void 0 != a) {
            debug && console.info("WANote: Will add options");
            var b = document.createElement("div");
            b.setAttribute("class", "menu-item menu-item-whatsnote");
            var c = document.createElement("button");
            c.setAttribute("class", "icon icon-whatsnote"),
            c.setAttribute("title", "WhatsNote"),
            b.appendChild(c),
            a.parentElement.insertBefore(b, a),
            chrome.runtime.sendMessage({
                name: "getOptions"
            },
            function(a) {
                debug && console.info("WANote: Got options: " + JSON.stringify(a)),
                backgroundNotif = a.backgroundNotif,
                wideText = a.wideText;
                var b = window.location.hash;
                "string" == typeof b && 0 == b.indexOf(optionsFragment) && (history.replaceState({},
                document.title, "/"), setTimeout(function() {},
                safetyDelayLong))
            })
        }
    } catch(d) {
        console.error("WANote: Exception while adding options"),
        console.error(d)
    }
}
function optionBackgroundNotifClick() {
    var a = document.querySelector("#whatsnote-option-background-notif .checkbox-whatsnote"),
    b = a.getAttribute("class");
    b.indexOf("unchecked") > -1 ? (a.setAttribute("class", b.replace("unchecked", "checked")), backgroundNotif = !0) : (a.setAttribute("class", b.replace("checked", "unchecked")), backgroundNotif = !1),
    chrome.runtime.sendMessage({
        name: "setOptions",
        backgroundNotif: backgroundNotif
    })
}
function optionWideTextClick() {
    var a = document.querySelector("#whatsnote-option-wide-text .checkbox-whatsnote"),
    b = a.getAttribute("class");
    b.indexOf("unchecked") > -1 ? (a.setAttribute("class", b.replace("unchecked", "checked")), wideText = !0) : (a.setAttribute("class", b.replace("checked", "unchecked")), wideText = !1),
    chrome.runtime.sendMessage({
        name: "setOptions",
        wideText: wideText
    }),
    updateWideText()
}
function optionRateClick() {
    window.open(rateUrl)
}
function updateWideText() {
    debug && console.info("WANote: Updating wide text..."),
    void 0 == wideTextStyleElem && (wideTextStyleElem = document.createElement("style"), wideTextStyleElem.setAttribute("type", "text/css"), wideTextStyleElem.innerHTML = ".message-in, .message-out { max-width: 100% !important; }"),
    wideText && void 0 == wideTextStyleElem.parentElement ? (debug && console.info("WANote: Will update wide text"), document.getElementsByTagName("head")[0].appendChild(wideTextStyleElem)) : wideText || void 0 == wideTextStyleElem.parentElement || (debug && console.info("WANote: Will update wide text"), wideTextStyleElem.parentElement.removeChild(wideTextStyleElem))
}
function sendPush() {
    sendbutton = document.getElementsByClassName("compose-btn-send"),
    1 == sendbutton.length ? sendbutton[0].click() : window.setTimeout(sendPush, 1e3)
}
function getMensajes() {
    var a = JSON.parse(JSON.stringify(Store.Chat))[0].msgs,
    b = [];
    if (a.length > 0) for (i = 0; i < a.length; i++) {
        var c = a[i].body;
        b.push(c)
    }
    return b
}
function injectScript(a, b) {
    var c = document.getElementsByTagName(b)[0],
    d = document.createElement("script");
    d.setAttribute("type", "text/javascript"),
    d.setAttribute("src", a),
    c.appendChild(d)
}
var debug = !1,
debugRepeating = !1,
whatsAppUrl = "https://web.whatsapp.com/",
rateUrl = "https://chrome.google.com/webstore/detail/whatsnote/hmjdomiopbnjebknokngdefkkkpjknld/reviews",
optionsFragment = "#watOptions",
sourceChatFragment = "#watSrcChatTitle=",
safetyDelayShort = 300,
safetyDelayLong = 600,
checkBadgeInterval = 5e3,
checkLoadingErrorInterval = 3e4,
backgroundNotif = !0,
wideText = !1,
taggedcontactspreloaded = !1,
openedchat = "WhatsDock",
scriptElem = document.createElement("script");
scriptElem.innerHTML = "window.onbeforeunload = null;",
document.head.appendChild(scriptElem),
chrome.runtime.sendMessage({
    name: "getIsBackgroundPage"
},
function(a) {
    a ? (debug && console.info("WANote: Background script injected"), backgroundScript()) : (debug && console.info("WANote: Foreground script injected"), foregroundScript()),
    chrome.runtime.sendMessage({
        name: "getOptions"
    },
    function(b) {
        debug && console.info("WANote: Got options: " + JSON.stringify(b)),
        a || updateWideText()
    })
}),
setInterval(function() {
    var a = document.getElementsByClassName("chatlist-panel-body");
    if (a.length > 0) {
        null === document.querySelector(".pane") && updatepanes && wdlauncher("panesblockclass");
        var b = document.getElementsByClassName("PhoneClass");
        document.getElementsByClassName("chatlist-panel-body").length > 0 && (0 == b.length || b[0] !== a[0].childNodes[0] ? inputsearchphoneshowfunction() : document.getElementById("phonetosend").hasAttribute("empty") && "" == document.getElementById("phonetosend").value && (document.getElementById("phonetosend").value = getMyNum(), "" !== document.getElementById("phonetosend").value && document.getElementById("phonetosend").removeAttribute("empty")));
        var c = document.getElementsByClassName("wdfilter");
        0 == c.length && insertFilterPanel(),
        taggedcontactspreloaded || (preloadtaggedcontacts(), taggedcontactspreloaded = !0)
    }
    if (null !== document.getElementById("main") && document.getElementById("main").getElementsByClassName("pane-chat-header").length > 0) {
        var d = "WhatsDock";
        if (document.getElementById("main").getElementsByClassName("chat-title").length > 0 && document.getElementById("main").getElementsByClassName("chat-title")[0].getElementsByTagName("span").length > 0 && (d = document.getElementById("main").getElementsByClassName("chat-title")[0].getElementsByTagName("span")[0].getAttribute("title")), openedchat !== d && document.getElementById("main").getElementsByClassName("chat-avatar").length > 0 && window.innerWidth > 1024) {
            openedchat = d;
            var e = document.getElementById("main").getElementsByClassName("chat-avatar")[0];
            null === e.parentElement.getAttribute("active") && (e.parentElement.addEventListener("click",
            function(a) {
                localStorage.wdpanelclose = !1
            }), e.parentElement.setAttribute("active", !0)),
            "undefined" != typeof localStorage.wdpanelclose && "true" === localStorage.wdpanelclose || e.click(),
            inyectcontactpanel()
        }
    }
    colorcontacts("pending")
},
1e3);
var lastToolbarIconWarn = -1,
lastToolbarIconBadgeText = -1,
lastToolbarIconTooltipText = -1,
lastPotentialLoadingError = !1,
wideTextStyleElem, userMsgPrepare = function(a, b) {
    wdlauncher("openchatat", {
        id: a + "@c.us",
        msg: b
    })
};
chrome.runtime.onMessage.addListener(function(a, b, c) {
    if (a.mynumber && "string" == typeof a.message) {
        var d = a.mynumber,
        e = a.message;
        userMsgPrepare(d, e),
        "" !== e ? a.wdsource && trackSendEvent(a.wdsource) : a.wdsource && trackSendEvent(a.wdsource, !0),
        c({
            result: "done"
        })
    } else if (a.chatlist) {
        var f = getMensajes();
        c({
            result: "ok",
            chatlist: f
        })
    } else if (a.deletemsg) {
        var g = "Store.Chat.get(Store.Conn.me).msgs.get('" + a.deletemsg + "')",
        h = document.createElement("script"),
        i = "webpackJsonp([], null, [12])",
        j = "Store.Chat",
        k = j + ".find(" + j + ".get(Store.Conn.me).id).then(function(t) {" + i + ".openChatFromUnread(t).then(function(e) {" + i + ".focusChatTextInput(t)})});";
        k += i + ".sendDeleteMsgs(" + g + ".chat,[" + g + "]);",
        h.innerHTML = k,
        document.body.appendChild(h),
        h.remove(),
        c({
            result: "ok"
        })
    } else a.showinfowindow ? (showphoneinfo(), c({
        result: "ok"
    })) : a.getcontactexists ? (wdlauncher("idexists", {
        id: a.getcontactexists,
        tabid: a.tabid
    }), c({
        result: "ok"
    })) : c({
        result: "fail"
    });
    return ! 0
}),
injectScript(chrome.extension.getURL("store.js"), "body"),
startApp();